import * as fs from "fs";
import moment from "moment";
import path from "path";
import jwt, {JwtPayload} from 'jsonwebtoken';

class Jwt {
    data: string | number

    constructor(data: string | number) {
        this.data = data
    }

    /** 生成token **/
    generateToken() {
        const data = this.data
        const tokenTimeEnd = Date.now();
        //私钥加密
        const cert = fs.readFileSync(path.join(__dirname, "../../rsa_private_key.pem"))
        console.log('generateToken------------cert', cert)
        const token = jwt.sign({
            data, exp:  tokenTimeEnd+ 60 * 30 * 1000
        }, cert, {algorithm: "RS256"})
        console.log('generateToken----------token', token)
        return token
    }

    /** 验证token **/
    verifyToken() {
        const token = this.data
        const cert = fs.readFileSync(path.join(__dirname, "../../rsa_public_key.pem"))
        let res;
        try {
            const result:JwtPayload | string  = jwt.verify(token as string, cert, {algorithms: ["RS256"]}) || {}
            console.log('verifyToken-----------------result',result)
            const current = Date.now();
            let exp=0

            if (current <= exp) {
                res = result
            }
        } catch (err) {
            res = err
        }
        return res
    }

}